import asyncio
import random
import math
from pathlib import Path


class AsyncAwaitExample:
    async def fetch_data(self, delay: int) -> str:
        print("开始获取数据...")
        await asyncio.sleep(delay)
        data = [
            {
                "id": f"A001{math.floor(random.random()*1000)}",
                "age": f"{math.floor(random.random()*100)}",
            }
            for i in range(100)
        ]
        print("数据获取完成，开发返回")
        return data

    async def process_data(self, data: str) -> str:
        print("开始处理数据...")
        await asyncio.sleep(1)
        processed = [item for item in data if int(item["age"]) > 30]
        print("数据处理完成，返回结果")
        return processed

    async def main(self):
        data = await self.fetch_data(2)
        print("获取到的数据=", data)
        processed_data = await self.process_data(data)
        print(processed_data)


# 执行异步示例
# example = AsyncAwaitExample()
# asyncio.run(example.main())

"""
执行一个并发操作
1.一个任务生成数据
2.另一个任务处理数据
3.使用async和await关键字实现异步编程
"""


class ConcurrentAsyncExample:

    async def open_file_read(self, filename="金融渠道账单.csv"):

        print(f"开始读取文件 {filename} ...")
        file_path = Path(__file__).parent / filename
        await asyncio.sleep(1)
        with open(file_path, "r", encoding="utf-8") as file:
            content = file.read()

        if content is not None:
            print(f"文件 {filename} 读取完成，返回内容")
            return content

        return None

    async def generate_data(self, taskId):
        print(f"1.{taskId}开始生成数据...")
        await asyncio.sleep(1)
        data = [
            {
                "id": f"B001{math.floor(random.random()*1000)}",
                "age": f"{math.floor(random.random()*100)}",
            }
            for i in range(2)
        ]
        print(f"2.{taskId}数据生成完成，返回数据")
        return data

    async def analyze_data(self, taskId: int):
        print(f"1.{taskId}数据生成中.....")
        await asyncio.sleep(1)
        data = [
            {
                "id": f"B001_{i}__{math.floor(random.random()*1000)}",
                "age": math.floor(random.random() * 100),
            }
            for i in range(100)
        ]

        print(f"2..{taskId}开始分析数据...")
        analyzed = [item for item in data if item["age"] < 50]
        print(f"3.{taskId}数据分析完成，返回结果")
        return analyzed

    async def batch_generate_tasks(self, delay):
        task_list = []
        await asyncio.sleep(delay)
        for i in range(5):
            task = self.generate_data(i)
            task_list.append(task)

        return task_list

    async def concurrent_main(self):
        # task_list = await self.batch_generate_tasks(1)
        task_list = [
            self.open_file_read(),
            self.analyze_data(1),
            self.generate_data(1),
        ]
        results = await asyncio.gather(*task_list)
        # results = await asyncio_execute
        for result in results:
            print("并发任务结果=", result)


# 执行并发异步示例
concurrentAsyncExample = ConcurrentAsyncExample()
asyncio.run(concurrentAsyncExample.concurrent_main())
